import os
import json
from django.utils import timezone
from home.models import CommunityPost
from Login.models import User

def run():
    # 获取或创建一个默认用户
    user, _ = User.objects.get_or_create(username='tieba爬虫', defaults={
        'avatar': '', 'level': 1, 'points': 0
    })

    file_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'tieba_posts_20.json')
    with open(file_path, 'r', encoding='utf-8') as f:
        data = json.load(f)

    for item in data:
        CommunityPost.objects.create(
            user=user,
            title=item.get('title', ''),
            content=item.get('content', ''),
            images=item.get('images', []),
            duration=item.get('duration', ''),
            pace=item.get('pace', ''),
            calorie=item.get('calorie', ''),
            created_at=item.get('created_at', timezone.now())
        )
    print('导入完成！')
